package ngat.oss.simulation;

import java.util.*;

public class EnhancedAccountingModel implements AccountingModel {

    /** Model to be enhanced.*/
    AccountingModel baseModel;

   /** Stores latest temporary accounts.*/
    private Map tempAccounts;

    /** Create an EnhancedAccountingModel on the specified base model.*/
    public EnhancedAccountingModel(AccountingModel baseModel) {
	this.baseModel = baseModel;
	tempAccounts = new HashMap();
    }


    /** Get a specific proposal's accounts.*/
    public Accounts getAccounts(String path) throws Exception {

	if (tempAccounts.containsKey(path)) {
	    Accounts acc = (Accounts)tempAccounts.get(path);
	    return acc;
	}
	return baseModel.getAccounts(path);
    }

    /** Setup temporary accounts to match existing accounts.*/
    public void resetTemporaryAccounts() {

	// first clear out any already setup
	Iterator it = tempAccounts.keySet().iterator();
	while (it.hasNext()) {
	    String path = (String)it.next();
	    Accounts accs = (Accounts)tempAccounts.get(path);
	    accs.clear();
	    accs = null;
	}	    
	tempAccounts.clear();


	// iterate over all proposal accounts
	Iterator ig = tempAccounts.keySet().iterator();
	while (ig.hasNext()) {
	    String path = (String)ig.next();
	    Accounts accounts = (Accounts)tempAccounts.get(path);

	    // create false accounts
	    Accounts falseAccounts = new Accounts();

	    tempAccounts.put(path, falseAccounts);

	    // iterate over all accounts   
	    Iterator ia = accounts.listAccountIds();
	    while (ia.hasNext()) {
		Integer aid = ((Integer)ia.next());
		int acid = aid.intValue();
		Account acc = (Account)accounts.getAccount(acid);
		Account facc = new Account(acc.getAllocated(), acc.getUsed());
		falseAccounts.addAccount(acid, facc);
	    }
	}

    }

}
